import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/LoginView.vue'),
      meta: { requiresAuth: false }
    },
    {
      path: '/',
      name: 'Layout',
      component: () => import('@/layout/AdminLayout.vue'),
      redirect: '/dashboard',
      meta: { requiresAuth: true },
      children: [
        {
          path: 'dashboard',
          name: 'Dashboard',
          component: () => import('@/views/DashboardView.vue'),
          meta: {
            title: '首页',
            icon: 'House',
            requiresAuth: true
          }
        },
        {
          path: 'products',
          name: 'Products',
          component: () => import('@/views/ProductsView.vue'),
          meta: {
            title: '商品管理',
            icon: 'Goods',
            requiresAuth: true
          }
        },
        {
          path: 'products/create',
          name: 'ProductCreate',
          component: () => import('@/views/ProductFormView.vue'),
          meta: {
            title: '新建商品',
            requiresAuth: true,
            hideInMenu: true
          }
        },
        {
          path: 'products/edit/:id',
          name: 'ProductEdit',
          component: () => import('@/views/ProductFormView.vue'),
          meta: {
            title: '编辑商品',
            requiresAuth: true,
            hideInMenu: true
          }
        },
        {
          path: 'users',
          name: 'Users',
          component: () => import('@/views/UsersView.vue'),
          meta: {
            title: '用户管理',
            icon: 'User',
            requiresAuth: true
          }
        },
        {
          path: 'categories',
          name: 'Categories',
          component: () => import('@/views/CategoriesView.vue'),
          meta: {
            title: '分类管理',
            icon: 'Menu',
            requiresAuth: true
          }
        },
        {
          path: 'orders',
          name: 'Orders',
          component: () => import('@/views/OrdersView.vue'),
          meta: {
            title: '订单管理',
            icon: 'Document',
            requiresAuth: true
          }
        },
        {
          path: 'orders/:id',
          name: 'OrderDetail',
          component: () => import('@/views/OrderDetailView.vue'),
          meta: {
            title: '订单详情',
            requiresAuth: true,
            hideInMenu: true
          }
        },
        {
          path: 'system',
          name: 'System',
          component: () => import('@/views/SystemView.vue'),
          meta: {
            title: '系统设置',
            icon: 'Setting',
            requiresAuth: true
          }
        },
        {
          path: 'miniapp-images',
          name: 'MiniappImages',
          component: () => import('@/views/MiniappImagesView.vue'),
          meta: {
            title: '小程序图片',
            icon: 'Picture',
            requiresAuth: true
          }
        },
        {
          path: 'cooperation-applications',
          name: 'CooperationApplications',
          component: () => import('@/views/CooperationApplicationsView.vue'),
          meta: {
            title: '合作申请',
            icon: 'Message',
            requiresAuth: true
          }
        }
      ]
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'NotFound',
      component: () => import('@/views/NotFoundView.vue')
    }
  ]
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore()

  // 如果路由需要认证
  if (to.meta.requiresAuth !== false) {
    if (!authStore.isLoggedIn) {
      // 未登录，跳转到登录页
      next('/login')
      return
    }

    // 如果有token但没有用户信息，尝试获取用户信息
    if (authStore.token && !authStore.user) {
      try {
        await authStore.fetchUserInfo()
      } catch (error) {
        // 获取用户信息失败，跳转到登录页
        next('/login')
        return
      }
    }
  }

  // 如果已登录且访问登录页，重定向到首页
  if (to.name === 'Login' && authStore.isLoggedIn) {
    next('/')
    return
  }

  next()
})

export default router
